package cn.car91.activity;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Base64;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.GeolocationPermissions.Callback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.car91.R;
import cn.car91.adapter.IllegalAreaAdapter;
import cn.car91.adapter.IllegalCarsListAdapter;
import cn.car91.bean.IllegalCar;
import cn.car91.utils.MobileUtils;
import cn.car91.utils.RegexUtil;
import cn.car91.view.HerilyAlertDialog;
import cn.car91.view.MyGridView;
import cn.car91.view.MyListView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.util.LogUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.lidroid.xutils.view.annotation.event.OnItemClick;
import com.thinkland.sdk.android.DataCallBack;
import com.thinkland.sdk.android.JuheData;
import com.thinkland.sdk.android.Parameters;

public class IllegalMainActivity extends BaseActivity {

    SharedPreferences carPreference;

    @ViewInject(R.id.soft_illegal)
    LinearLayout softView;
    @ViewInject(R.id.web_illegal)
    WebView webView;
    @ViewInject(R.id.cx_city)
    ViewGroup currentArea;
    @ViewInject(R.id.illegal_province)
    MyGridView provincesView;
    @ViewInject(R.id.illegal_city)
    MyGridView cityView;
    @ViewInject(R.id.chepai_sz)
    TextView shortnameView;
    @ViewInject(R.id.cartype_sz)
    TextView cartypeView;
    @ViewInject(R.id.chepai_number)
    EditText carNoView;
    @ViewInject(R.id.chejia_number)
    EditText carClsView;
    @ViewInject(R.id.engine_number)
    EditText carEngView;
    @ViewInject(R.id.regist_number)
    EditText carRegView;
    @ViewInject(R.id.my_carno)
    TextView curCarView;
    @ViewInject(R.id.illegal_cars)
    MyListView myCarsView;
    @ViewInject(R.id.illegal_input)
    View illegalInputView;
    @ViewInject(R.id.illegal_choose_cars)
    View illegalChooseView;
    @ViewInject(R.id.my_cars)
    View carsButton;

    IllegalCarsListAdapter illegalCarsListAdapter;
    IllegalAreaAdapter provincesAdapter;
    IllegalAreaAdapter citysAdapter;

    Map<String, List<JSONObject>> cities = new HashMap<String, List<JSONObject>>();
    List<String> shortnames = new ArrayList<String>();
    List<String> cartypes = new ArrayList<String>();

    @ViewInject(R.id.back_btn)
    View backView;

    private IllegalCar curCar = null;

//    final String url = "http://m.cheshouye.com/api/weizhang/?t=fc4302";
//    final String url = "http://wap.cx580.com/ViolationQuery.aspx";
    final String areaUrl = "http://v.juhe.cn/wz/citys";
    final String typeUrl = "http://v.juhe.cn/wz/hpzl";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        setContentView(R.layout.activity_illegal_main);
        super.onCreate(savedInstanceState);
        //获取android手机的唯一ID
        //String t=android.provider.Settings.System.getString(getContentResolver(), "android_id"); 
        //Log.v("this","android_id="+t);
        //LogUtils.e(getCar91Application().getConfigsMap().get("illegal_url"));
        ((TextView) findViewById(R.id.header_text)).setText("违章查询");
        if (getCar91Application().getConfigsMap().containsKey("illegal_url")) {
            String illegalUrl = getCar91Application().getConfigsMap().get("illegal_url");
            if (RegexUtil.isNotNull(illegalUrl)) {
                if(illegalUrl.contains("app.car91.cn/illegal.jsp")){
                    String uid = null;
                    if(getCar91Application().getUser()!=null){
                        try {
                            uid = MessageDigest.getInstance("MD5").digest(getCar91Application().getUser().getId().getBytes("UTF-8")).toString();
                        } catch (Exception e) { }
                    }
                    
                    if(RegexUtil.isNull(uid)){
                        try {
                            uid = Base64.encodeToString(MobileUtils.getDeviceId(IllegalMainActivity.this).getBytes("UTF-8"), Base64.DEFAULT);
                        } catch (UnsupportedEncodingException e) {
                            getDefaultData();
                            return;
                        }
                    }
                    

                    if(!illegalUrl.endsWith("?")) {
                        illegalUrl += "?";
                    }
                    illegalUrl += "uid="+uid;
                }
                
                softView.setVisibility(View.GONE);
                webView.setVisibility(View.VISIBLE);
                WebSettings settings = webView.getSettings();
                settings.setJavaScriptEnabled(true);
                settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
                String dir = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath(); 
                //启用地理定位  
                settings.setGeolocationEnabled(true);  
                //设置定位的数据库路径  
                settings.setGeolocationDatabasePath(dir);   
                //最重要的方法，一定要设置，这就是出不来的主要原因
                settings.setDomStorageEnabled(true);
                webView.setWebChromeClient(new WebChromeClient(){
        			@Override
        			public void onGeolocationPermissionsShowPrompt(String origin,
        					Callback callback) {
        				callback.invoke(origin, true, false);
        				super.onGeolocationPermissionsShowPrompt(origin, callback);
        			}
                });
                webView.setWebViewClient(new WebViewClient() {
            	    public boolean shouldOverrideUrlLoading(WebView view, String url)
            	    { //  重写此方法表明点击网页里面的链接还是在当前的webview里跳转，不跳到浏览器那边
            	    	view.loadUrl(url);
            	    	return true;
            	    }
            	});

                webView.loadUrl(illegalUrl);
                return;
            }
        }

        getDefaultData();
    }
    
    private void getDefaultData(){
        carPreference = this.getPreferences(MODE_PRIVATE);

        provincesAdapter = new IllegalAreaAdapter(IllegalMainActivity.this);
        provincesView.setAdapter(provincesAdapter);

        citysAdapter = new IllegalAreaAdapter(IllegalMainActivity.this);
        cityView.setAdapter(citysAdapter);

        initLastCar();
        ((View) shortnameView.getParent()).setOnClickListener(onShortNameClick);
        ((View) cartypeView.getParent()).setOnClickListener(onCarTypeClick);

        getData();
    }

    @Override
    protected void onResume() {
        initCars();
        super.onResume();
    }

    private void getData() {
        JuheData.executeWithAPI(getCar91Application().apiIllegalId, areaUrl, JuheData.POST, new Parameters(), new DataCallBack() {
                    @Override
                    public void resultLoaded(int err, String reason, String result) {
                        if (err == 0) {
                            try {
                                JSONObject jsonObject = JSONObject.parseObject(result);
                                if (jsonObject.getString("resultcode").equals("200")) {
                                    JSONObject jsonObjs = jsonObject.getJSONObject("result");
                                    List<IllegalAreaAdapter.Area> areas = new ArrayList<IllegalAreaAdapter.Area>();
                                    Set<Entry<String, Object>> provinces = jsonObjs.entrySet();
                                    for (Entry<String, Object> entry : provinces) {
                                        IllegalAreaAdapter.Area area = provincesAdapter.instanceArea();
                                        area.id = entry.getKey();
                                        JSONObject tmp = (JSONObject) entry.getValue();
                                        area.name = tmp.getString("province");
                                        JSONArray tmpArray = tmp.getJSONArray("citys");
                                        List<JSONObject> cityObj = new ArrayList<JSONObject>();
                                        for (int i = 0; i < tmpArray.size(); i++) {
                                            JSONObject tobj = tmpArray.getJSONObject(i);
                                            if (i == 0) {
                                                shortnames.add(tobj.getString("abbr"));
                                            }
                                            cityObj.add(tobj);
                                        }
                                        areas.add(area);
                                        cities.put(area.id, cityObj);
                                    }
                                    provincesAdapter.setmList(areas);
                                    provincesAdapter.notifyDataSetChanged();
                                }
                            } catch (Exception e) {
                            }
                        } else {
                            Toast.makeText(getApplicationContext(), reason, Toast.LENGTH_SHORT).show();
                        }
                    }
                }
        );

        JuheData.executeWithAPI(getCar91Application().apiIllegalId, typeUrl, JuheData.POST, new Parameters(), new DataCallBack() {
            @Override
            public void resultLoaded(int err, String reason, String result) {
                if (err == 0) {
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    if (jsonObject.getString("resultcode").equals("200")) {
                        JSONArray jsonArys = jsonObject.getJSONArray("result");
                        for (int i = 0; i < jsonArys.size(); i++) {
                            cartypes.add(jsonArys.getJSONObject(i).getString("id") + "_" + jsonArys.getJSONObject(i).getString("car"));
                        }
                    }
                }
            }
        });
    }

    @OnClick(R.id.cx_city)
    public void onCitysClick(View view) {
        View areaRow = (View) provincesView.getParent().getParent();
        provincesView.setVisibility(View.VISIBLE);
        cityView.setVisibility(View.GONE);
        if (areaRow.getVisibility() == View.VISIBLE) {
            areaRow.setVisibility(View.GONE);
            ((ImageView) currentArea.getChildAt(1)).setImageResource(R.drawable.forward);
        } else {
            areaRow.setVisibility(View.VISIBLE);
            ((ImageView) currentArea.getChildAt(1)).setImageResource(R.drawable.drop);
        }
    }

    @OnItemClick(R.id.illegal_province)
    public void onProvinceItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
        String pid = ((TextView) arg1.findViewById(R.id.area_id)).getText().toString();
        List<JSONObject> citysObject = cities.get(pid);
        List<IllegalAreaAdapter.Area> areas = new ArrayList<IllegalAreaAdapter.Area>();
        for (JSONObject jsonObject : citysObject) {
            IllegalAreaAdapter.Area area = citysAdapter.instanceArea();
            String city_code = jsonObject.getString("city_code");
            String city_name = jsonObject.getString("city_name");
            String abbr = jsonObject.getString("abbr");
            String engine = jsonObject.getString("engine");
            String engineno = jsonObject.getString("engineno");
            String iclass = jsonObject.getString("classa");
            String classno = jsonObject.getString("classno");
            String regist = jsonObject.getString("regist");
            String registno = jsonObject.getString("registno");
            area.id = "city_code=" + city_code + ",;" + "city_name=" + city_name + ",;" + "abbr=" + abbr + ",;" +
                    "engine=" + engine + ",;" + "engineno=" + engineno + ",;" + "classa=" + iclass + ",;" +
                    "classno=" + classno + ",;" + "regist=" + regist + ",;" + "registno=" + registno;
            area.name = jsonObject.getString("city_name");
            areas.add(area);
        }
        citysAdapter.setmList(areas);
        citysAdapter.notifyDataSetChanged();
        provincesView.setVisibility(View.GONE);
        cityView.setVisibility(View.VISIBLE);
    }

    @OnItemClick(R.id.illegal_city)
    public void onCityItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                long arg3) {
        View areaRow = (View) cityView.getParent().getParent();
        areaRow.setVisibility(View.GONE);
        provincesView.setVisibility(View.VISIBLE);
        cityView.setVisibility(View.GONE);

        String cid = ((TextView) arg1.findViewById(R.id.area_id)).getText().toString();
        String[] tmp = cid.split(",;");
        Editor editor = getCar91Application().getOtherPreferences().edit();
        for (String string : tmp) {
            String[] ttmp = string.split("=");
            editor.putString(ttmp[0], ttmp[1]);
        }
        editor.commit();
        initChoose();
    }

    @OnClick(R.id.my_cars)
    public void onMyCarClick(final View view) {
        initCars();
        illegalInputView.setVisibility(View.GONE);
        illegalChooseView.setVisibility(View.VISIBLE);
        backView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                onIllegalFormClick(view);
            }
        });
    }

    @OnClick(R.id.illegal_form)
    public void onIllegalFormClick(View view) {
        initCars();
        illegalChooseView.setVisibility(View.GONE);
        illegalInputView.setVisibility(View.VISIBLE);
        backView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                finish();
            }
        });
    }

    @OnClick(R.id.illegal_form_new)
    public void onIllegalFormNewClick(View view) {
        initCars();
        curCar = null;
        curCarView.setText("新车查询");
        clearCarInfo();
        initChoose();
        illegalChooseView.setVisibility(View.GONE);
        illegalInputView.setVisibility(View.VISIBLE);
        backView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                finish();
            }
        });
    }

    @OnClick(R.id.btn_query)
    public void onQueryClick(View view) {
        SharedPreferences preferences = getCar91Application().getOtherPreferences();
        String city_code = preferences.getString("city_code", "");
        String city_name = preferences.getString("city_name", getResources().getString(R.string.csy_cxdz_tip));
        String abbr = preferences.getString("abbr", "");
        String engine = preferences.getString("engine", "1");
        String iclass = preferences.getString("classa", "1");
        String regist = preferences.getString("regist", "0");
        String carid = preferences.getString("cartype_id", "02");
        String cartypename = preferences.getString("cartype_name", "小型车");
        String enginelength = preferences.getString("engineno", "0");
        String classlength = preferences.getString("classno", "0");
        String registlength = preferences.getString("registno", "0");

        String engineno = carEngView.getEditableText().toString();
        String classno = carClsView.getEditableText().toString();
        String carno = carNoView.getEditableText().toString();
        String registno = carRegView.getEditableText().toString();

        if (RegexUtil.isNull(city_code)) {
            new HerilyAlertDialog.Builder(IllegalMainActivity.this).setTitle("出错了").setMessage("请选择查询的地区").create().show();
            return;
        } else if (RegexUtil.isNull(abbr)) {
            new HerilyAlertDialog.Builder(IllegalMainActivity.this).setTitle("出错了").setMessage("请选择车牌前缀").create().show();
            return;
        } else if (RegexUtil.isNull(carno)) {
            new HerilyAlertDialog.Builder(IllegalMainActivity.this).setTitle("出错了").setMessage("请输入车牌号").create().show();
            carNoView.requestFocus();
            return;
        }

        StringBuffer params = new StringBuffer();
        if (engine.equals("1")) {
            if (RegexUtil.isNull(engineno)) {
                new HerilyAlertDialog.Builder(IllegalMainActivity.this).setTitle("出错了").setMessage("请输入发动机号").create().show();
                carEngView.requestFocus();
                return;
            } else
                params.append("engineno=" + carEngView.getEditableText().toString() + "&");
        }
        if (iclass.equals("1")) {
            if (RegexUtil.isNull(classno)) {
                new HerilyAlertDialog.Builder(IllegalMainActivity.this).setTitle("出错了").setMessage("请输入车架号").create().show();
                carClsView.requestFocus();
                return;
            } else
                params.append("classno=" + carClsView.getEditableText().toString() + "&");
        }
        if (regist.equals("1")) {
            if (RegexUtil.isNull(registno)) {
                new HerilyAlertDialog.Builder(IllegalMainActivity.this).setTitle("出错了").setMessage("请输入注册号").create().show();
                carRegView.requestFocus();
                return;
            } else
                params.append("regno=" + carClsView.getEditableText().toString() + "&");
        }

        params.append("city=" + city_code + "&");
        params.append("hphm=" + abbr + carno + "&");
        params.append("hpzl=" + carid);

        if (curCar == null) {
            curCar = new IllegalCar();
        }

        curCar.setCartype(carid);
        curCar.setCartypename(cartypename);
        curCar.setCitycode(city_code);
        curCar.setCityname(city_name);
        curCar.setCityshortname(abbr);
        try {
            curCar.setClasslength(Integer.parseInt(classlength));
        } catch (Exception e) {
        }
        try {
            curCar.setEnginelength(Integer.parseInt(enginelength));
        } catch (Exception e) {
        }
        try {
            curCar.setRegistlength(Integer.parseInt(registlength));
        } catch (Exception e) {
        }
        curCar.setClassno(classno);
        curCar.setEngineno(engineno);
        curCar.setNo(carno);
        curCar.setRegistno(registno);
        try {
            curCarView.setText(curCar.getCityshortname() + curCar.getNo());
            getCar91Application().getDbUtils().saveOrUpdate(curCar);
        } catch (DbException e) {
            LogUtils.e("车辆信息保存失败");
        }

        Editor editor = getCar91Application().getOtherPreferences().edit();
        editor.putString("icarno", carno);
        editor.putString("icareng", engineno);
        editor.putString("icarcls", classno);
        editor.commit();

        Intent intent = new Intent(IllegalMainActivity.this, IllegalResultActivity.class);
        intent.putExtra("params", params.toString());
        startActivity(intent);
    }

    OnClickListener onShortNameClick = new OnClickListener() {
        @Override
        public void onClick(View v) {
            Object[] tm = shortnames.toArray();
            final String[] sn = new String[tm.length];
            for (int i = 0; i < tm.length; i++) {
                sn[i] = (String) tm[i];
            }
            new HerilyAlertDialog.Builder(IllegalMainActivity.this).setCancelable(true).setItems(sn,new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					shortnameView.setText(sn[arg1]);
                    Editor editor = getCar91Application().getOtherPreferences().edit();
                    editor.putString("abbr", sn[arg1]);
                    editor.commit();
				}
            }).create().show();
        }
    };

    OnClickListener onCarTypeClick = new OnClickListener() {
        @Override
        public void onClick(View v) {
            Object[] tm = cartypes.toArray();
            final String[] sn = new String[tm.length];
            for (int i = 0; i < tm.length; i++) {
                sn[i] = (String) tm[i];
            }
            new HerilyAlertDialog.Builder(IllegalMainActivity.this).setCancelable(true).setTitle("车辆（号牌）种类").setItems(sn, new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					String[] t = sn[arg1].split("_");
                    cartypeView.setText(t[1]);
                    Editor editor = getCar91Application().getOtherPreferences().edit();
                    editor.putString("cartype_id", t[0]);
                    editor.putString("cartype_name", t[1]);
                    editor.commit();
				}
            }).setNegativeButton("取消", null).create().show();
        }
    };

    private void initChoose() {
        try {
            SharedPreferences preferences = getCar91Application().getOtherPreferences();
            String city_name = preferences.getString("city_name", getResources().getString(R.string.csy_cxdz_tip));
            String abbr = preferences.getString("abbr", "");
            String engine = preferences.getString("engine", "1");
            String engineno = preferences.getString("engineno", "0");
            String iclass = preferences.getString("classa", "1");
            String classno = preferences.getString("classno", "0");
            String regist = preferences.getString("regist", "0");
            String registno = preferences.getString("registno", "0");
            String cartype = preferences.getString("cartype_name", "");
            //String cartype_id=preferences.getString("cartype_id","02");
            String icarno = preferences.getString("icarno", "");
            String icareng = preferences.getString("icareng", "");
            String icarcls = preferences.getString("icarcls", "");

            ((TextView) currentArea.getChildAt(0)).setText(city_name);
            shortnameView.setText(abbr);

            cartypeView.setText(cartype);
            carClsView.setText(icarcls);
            carNoView.setText(icarno);
            carEngView.setText(icareng);

            carNoView.addTextChangedListener(new TextWatcher() {
                int index = 0;

                @Override
                public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                }

                @Override
                public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                              int arg3) {
                }

                @Override
                public void afterTextChanged(Editable arg0) {
                    try {
                        carNoView.removeTextChangedListener(this);//解除文字改变事件
                        index = carNoView.getSelectionStart();//获取光标位置
                        carNoView.setText(arg0.toString().toUpperCase(Locale.CHINESE));//转换
                        carNoView.setSelection(index);//重新设置光标位置
                        carNoView.addTextChangedListener(this);//重新绑定事件
                    } catch (Exception e) {
                    }
                }
            });

            carClsView.addTextChangedListener(new TextWatcher() {
                int index = 0;

                @Override
                public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                }

                @Override
                public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                              int arg3) {
                }

                @Override
                public void afterTextChanged(Editable arg0) {
                    try {
                        carClsView.removeTextChangedListener(this);//解除文字改变事件
                        index = carClsView.getSelectionStart();//获取光标位置
                        carClsView.setText(arg0.toString().toUpperCase(Locale.CHINESE));//转换
                        carClsView.setSelection(index);//重新设置光标位置
                        carClsView.addTextChangedListener(this);//重新绑定事件
                    } catch (Exception e) {
                    }
                }
            });

            if (engine.equals("1")) {
                findViewById(R.id.row_engine).setVisibility(View.VISIBLE);
                ((EditText) findViewById(R.id.engine_number)).setMaxEms(Integer.parseInt(engineno));
            } else {
                findViewById(R.id.row_engine).setVisibility(View.GONE);
            }
            if (iclass.equals("1")) {
                findViewById(R.id.row_chejia).setVisibility(View.VISIBLE);
                ((EditText) findViewById(R.id.chejia_number)).setMaxEms(Integer.parseInt(classno));
            } else {
                findViewById(R.id.row_chejia).setVisibility(View.GONE);
            }
            if (regist.equals("1")) {
                findViewById(R.id.row_regist).setVisibility(View.VISIBLE);
                ((EditText) findViewById(R.id.regist_number)).setMaxEms(Integer.parseInt(registno));
            } else {
                findViewById(R.id.row_regist).setVisibility(View.GONE);
            }
        } catch (Exception e) {
            LogUtils.e(e.toString());
        }
    }

    private void initLastCar() {
        int icid = getCar91Application().getOtherPreferences().getInt("illcarid", 0);

        try {
            if (icid > 0)
                curCar = getCar91Application().getDbUtils().findById(IllegalCar.class, icid);
        } catch (DbException e) {
        }

        printCarInfo();
    }

    private void initCars() {
        try {
            final List<IllegalCar> cars = getCar91Application().getDbUtils().findAll(IllegalCar.class);
            if (cars != null && cars.size() > 0) {
                illegalCarsListAdapter = new IllegalCarsListAdapter(IllegalMainActivity.this);
                illegalCarsListAdapter.setMycars(cars);
                myCarsView.setAdapter(illegalCarsListAdapter);
                carsButton.setVisibility(View.VISIBLE);
                myCarsView.setOnItemLongClickListener(new OnItemLongClickListener() {
                    @Override
                    public boolean onItemLongClick(AdapterView<?> arg0,
                                                   View view, int arg2, long arg3) {
                        View delView = view.findViewById(R.id.car_delete);
                        if (delView.getVisibility() == View.VISIBLE) {
                            delView.setVisibility(View.GONE);
                            view.findViewById(R.id.car_besure).setVisibility(View.VISIBLE);
                        } else {
                            view.findViewById(R.id.car_besure).setVisibility(View.GONE);
                            delView.setVisibility(View.VISIBLE);
                        }
                        return true;
                    }
                });
            } else {
                carsButton.setVisibility(View.GONE);
            }
        } catch (DbException e) {
            //onIllegalFormClick(new TextView(this));
            carsButton.setVisibility(View.GONE);
        }
    }

    private void printCarInfo() {
        try {
            if (curCar != null) {
                curCarView.setText(curCar.getCityshortname() + curCar.getNo());
                Editor editor = getCar91Application().getOtherPreferences().edit();
                editor.putString("lastcar", curCar.getCityshortname() + curCar.getNo());
                editor.putString("icarno", curCar.getNo());
                editor.putString("icareng", curCar.getEngineno());
                editor.putString("icarcls", curCar.getClassno());
                editor.putString("abbr", curCar.getCityshortname());
                editor.putString("city_code", curCar.getCitycode());
                editor.putString("cartype_id", curCar.getCartype());
                editor.putString("cartype_name", curCar.getCartypename());
                editor.putString("city_name", curCar.getCityname());
                editor.putString("engineno", String.valueOf(curCar.getEnginelength()));
                editor.putString("classno", String.valueOf(curCar.getClasslength()));
                editor.putString("registno", String.valueOf(curCar.getRegistlength()));
                if (RegexUtil.isNotNull(curCar.getEngineno())) {
                    editor.putString("engine", "1");
                } else {
                    editor.putString("engine", "0");
                }
                if (RegexUtil.isNotNull(curCar.getClassno())) {
                    editor.putString("classa", "1");
                } else {
                    editor.putString("classa", "0");
                }
                if (RegexUtil.isNotNull(curCar.getRegistno())) {
                    editor.putString("regist", "1");
                } else {
                    editor.putString("regist", "0");
                }
                editor.commit();
                initChoose();
            }
        } catch (Exception e) {
        }
    }

    private void clearCarInfo() {
        Editor editor = getCar91Application().getOtherPreferences().edit();
        editor.putString("city_name", "");
        editor.putString("abbr", "");
        editor.putString("engine", "1");
        editor.putString("engineno", "0");
        editor.putString("classa", "1");
        editor.putString("classno", "0");
        editor.putString("regist", "0");
        editor.putString("registno", "0");
        editor.putString("cartype_name", "");
        editor.putString("cartype_id", "");
        editor.putString("icarno", "");
        editor.putString("icareng", "");
        editor.putString("icarcls", "");
        editor.commit();
    }

    @OnItemClick(R.id.illegal_cars)
    public void onIllegalCarItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                      long arg3) {
        try {
            curCar = illegalCarsListAdapter.getMycars().get(arg2);
            printCarInfo();
        } catch (Exception e) {
        }
        arg1.findViewById(R.id.car_delete).setVisibility(View.GONE);
        arg1.findViewById(R.id.car_besure).setVisibility(View.VISIBLE);
        onIllegalFormClick(arg1);
    }

    @Override
    protected void onDestroy() {
        if (curCar != null) {
            try {
                Editor editor = getCar91Application().getOtherPreferences().edit();
                editor.putInt("illcarid", curCar.getCid());
                editor.commit();
            } catch (Exception e) {
            }
        } else {
            clearCarInfo();
        }
        super.onDestroy();
    }
}
